<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="utf-8">
    <title>下载任务管理</title>
    <link rel="stylesheet" href="/app/admin/component/pear/css/pear.css"/>
    <link rel="stylesheet" href="/app/admin/admin/css/reset.css"/>
</head>
<body class="pear-container">

<!-- 顶部查询表单 -->
<div class="layui-card">
    <div class="layui-card-body">
        <form class="layui-form top-search-from">

            <div class="layui-form-item">
                <label class="layui-form-label">ID</label>
                <div class="layui-input-block">
                    <input type="number" name="id" value="" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">下载器ID</label>
                <div class="layui-input-block">
                    <input type="number" name="downloader_id" value="" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">站点ID</label>
                <div class="layui-input-block">
                    <input type="number" name="site_id" value="" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">种子ID</label>
                <div class="layui-input-block">
                    <input type="number" name="torrent_id" value="" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">下载状态</label>
                <div class="layui-input-block">
                    <div name="down_status" id="down_status" value=""></div>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">MediaInfo状态</label>
                <div class="layui-input-block">
                    <div name="mediaInfo_status" id="mediaInfo_status" value=""></div>
                </div>
            </div>

            <div class="layui-form-item layui-inline">
                <label class="layui-form-label"></label>
                <button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="table-query">
                    <i class="layui-icon layui-icon-search"></i>查询
                </button>
                <button type="reset" class="pear-btn pear-btn-md" lay-submit lay-filter="table-reset">
                    <i class="layui-icon layui-icon-refresh"></i>重置
                </button>
            </div>
            <div class="toggle-btn">
                <a class="layui-hide">展开<i class="layui-icon layui-icon-down"></i></a>
                <a class="layui-hide">收起<i class="layui-icon layui-icon-up"></i></a>
            </div>
        </form>
    </div>
</div>

<!-- 数据表格 -->
<div class="layui-card">
    <div class="layui-card-body">
        <table id="data-table" lay-filter="data-table"></table>
    </div>
</div>

<!-- 表格顶部工具栏 -->
<script type="text/html" id="table-toolbar">
    <!-- 不显示新增按钮，因为不支持新增数据 -->
    <button class="pear-btn pear-btn-danger pear-btn-md" lay-event="batchRemove" permission="app.admin.user.delete">
        <i class="layui-icon layui-icon-delete"></i>删除
    </button>
    <button class="pear-btn pear-btn-primary pear-btn-md" lay-event="retryDownload">
        <i class="layui-icon layui-icon-refresh"></i>重试失败任务
    </button>
    <button class="pear-btn pear-btn-primary pear-btn-md" lay-event="updateMediaInfo">
        <i class="layui-icon layui-icon-refresh"></i>更新媒体信息
    </button>
</script>

<!-- 表格行工具栏 -->
<script type="text/html" id="table-bar">
    <button class="pear-btn pear-btn-xs tool-btn" lay-event="edit" permission="app.admin.user.update">编辑状态</button>
    <button class="pear-btn pear-btn-xs tool-btn" lay-event="remove" permission="app.admin.user.delete">删除</button>
</script>

<script src="/app/admin/component/layui/layui.js?v=2.8.12"></script>
<script src="/app/admin/component/pear/pear.js"></script>
<script src="/app/admin/admin/js/permission.js"></script>
<script src="/app/admin/admin/js/common.js"></script>
<script>

    // 相关常量
    const PRIMARY_KEY = "id";
    const SELECT_API = "/app/csauto/torrenttask/select";
    const UPDATE_API = "/app/csauto/torrenttask/update";
    const DELETE_API = "/app/csauto/torrenttask/delete";
    const UPDATE_URL = "/app/csauto/torrenttask/update";

    // 下载状态下拉框
    layui.use(["jquery", "xmSelect"], function () {
        layui.$.ajax({
            url: "/app/csauto/api/get?name=download_status",
            dataType: "json",
            success: function (res) {
                let value = layui.$("#down_status").attr("value");
                let initValue = value ? value.split(",") : [];
                layui.xmSelect.render({
                    el: "#down_status",
                    name: "down_status",
                    initValue: initValue,
                    data: res.data,
                    model: {"icon": "hidden", "label": {"type": "text"}},
                    clickClose: true,
                    radio: true,
                });
                if (res.code) {
                    layui.popup.failure(res.msg);
                }
            }
        });
    });

    // MediaInfo状态下拉框
    layui.use(["jquery", "xmSelect"], function () {
        layui.$.ajax({
            url: "/app/csauto/api/get?name=mediainfo_status",
            dataType: "json",
            success: function (res) {
                let value = layui.$("#mediaInfo_status").attr("value");
                let initValue = value ? value.split(",") : [];
                layui.xmSelect.render({
                    el: "#mediaInfo_status",
                    name: "mediaInfo_status",
                    initValue: initValue,
                    data: res.data,
                    model: {"icon": "hidden", "label": {"type": "text"}},
                    clickClose: true,
                    radio: true,
                });
                if (res.code) {
                    layui.popup.failure(res.msg);
                }
            }
        });
    });

    // 表格渲染
    layui.use(["table", "form", "common", "popup", "util"], function () {
        let table = layui.table;
        let form = layui.form;
        let $ = layui.$;
        let common = layui.common;
        let util = layui.util;
        // 表头参数
        let cols = [
            {
                type: "checkbox"
            }, {
                title: "ID",
                field: "id",
                sort: true,
                width: 80,
            }, {
                title: "下载器ID",
                field: "downloader_id",
                width: 100,
            }, {
                title: "站点名称",
                field: "site_name",
                width: 150,
            }, {
                title: "种子ID",
                field: "torrent_id",
                width: 100,
            }, {
                title: "种子HASH",
                field: "torrent_hash",
                width: 200,
            }, {
                title: "种子状态",
                field: "status_text",
                templet: function (d) {
                    let statusMap = {
                        1: '<span style="color: #01AAED;">进行中</span>',
                        99: '<span style="color: #5FB878;">完结</span>'
                    };
                    return statusMap[d.status] || '未知状态';
                }
            }, {
                title: "下载状态",
                field: "down_status_text",
                templet: function (d) {
                    let statusMap = {
                        0: '<span style="color: #999;">待下载</span>',
                        1: '<span style="color: #01AAED;">下载中</span>',
                        2: '<span style="color: #5FB878;">下载完成</span>'
                    };
                    return statusMap[d.down_status] || '未知状态';
                }
            }, {
                title: "下载路径",
                field: "down_path",
                width: 300,
            }, {
                title: "MediaInfo状态",
                field: "mediaInfo_status_text",
                templet: function (d) {
                    let statusMap = {
                        0: '<span style="color: #999;">未获取</span>',
                        2: '<span style="color: #5FB878;">获取完成</span>'
                    };
                    return statusMap[d.mediaInfo_status] || '未知状态';
                }
            }, {
                title: "重试次数",
                field: "mediainfo_retry_count",
                width: 100,
            }, {
                title: "操作",
                toolbar: "#table-bar",
                align: "center",
                fixed: "right",
                width: 150,
            }
        ];

        // 渲染表格
        function render() {
            table.render({
                elem: "#data-table",
                url: SELECT_API,
                page: true,
                cols: [cols],
                skin: "line",
                size: "lg",
                toolbar: "#table-toolbar",
                autoSort: true,
                initSort: {
                    field: 'id',
                    type: 'desc'
                },
                defaultToolbar: [{
                    title: "刷新",
                    layEvent: "refresh",
                    icon: "layui-icon-refresh",
                }, "filter", "print", "exports"],
                done: function () {
                    layer.photos({photos: 'div[lay-id="data-table"]', anim: 5});
                }
            });
        }

        // 获取表格中下拉或树形组件数据
        let apis = [];
        let apiResults = {};
        let count = apis.length;
        layui.each(apis, function (k, item) {
            let [field, url] = item;
            $.ajax({
                url: url,
                dateType: "json",
                success: function (res) {
                    if (res.code) {
                        return layui.popup.failure(res.msg);
                    }

                    function travel(items) {
                        for (let k in items) {
                            let item = items[k];
                            apiResults[field][item.value] = item.name;
                            if (item.children) {
                                travel(item.children);
                            }
                        }
                    }

                    travel(res.data);
                },
                complete: function () {
                    if (--count === 0) {
                        render();
                    }
                }
            });
        });
        if (!count) {
            render();
        }

        // 编辑或删除行事件
        table.on("tool(data-table)", function (obj) {
            if (obj.event === "remove") {
                remove(obj);
            } else if (obj.event === "edit") {
                editStatus(obj);
            }
        });

        // 表格顶部工具栏事件
        table.on("toolbar(data-table)", function (obj) {
            if (obj.event === "refresh") {
                refreshTable();
            } else if (obj.event === "batchRemove") {
                batchRemove(obj);
            } else if (obj.event === "retryDownload") {
                layui.$.ajax({
                    url: "/app/csauto/api/retryDownload",
                    dataType: "json",
                    success: function (res) {
                        if (res.code === 0) {
                            layui.popup.success("下载重试任务已提交");
                        } else {
                            layui.popup.failure(res.msg || "下载重试失败");
                        }
                    },
                    error: function () {
                        layui.popup.failure("网络错误，下载重试失败");
                    }
                });
            } else if (obj.event === "updateMediaInfo") {
                layui.$.ajax({
                    url: "/app/csauto/api/updateMediaInfo",
                    dataType: "json",
                    success: function (res) {
                        if (res.code === 0) {
                            layui.popup.success("媒体信息更新任务已提交");
                        } else {
                            layui.popup.failure(res.msg || "媒体信息更新失败");
                        }
                    },
                    error: function () {
                        layui.popup.failure("网络错误，媒体信息更新失败");
                    }
                });
            }
        });

        // 表格顶部搜索事件
        form.on("submit(table-query)", function (data) {
            table.reload("data-table", {
                page: {
                    curr: 1
                },
                where: data.field
            })
            return false;
        });

        // 表格顶部搜索重置事件
        form.on("submit(table-reset)", function (data) {
            table.reload("data-table", {
                where: []
            })
        });

        // 表格排序事件
        table.on("sort(data-table)", function (obj) {
            table.reload("data-table", {
                initSort: obj,
                scrollPos: "fixed",
                where: {
                    field: obj.field,
                    order: obj.type
                }
            });
        });

        // 编辑状态
        let editStatus = function (obj) {
            let data = obj.data;
            layer.open({
                type: 1,
                title: "编辑下载任务状态",
                shade: 0.1,
                area: ["600px", "500px"],
                content: `
                    <div style="padding: 20px;">
                        <form class="layui-form" lay-filter="edit-status-form">
                            <div class="layui-form-item">
                                <label class="layui-form-label">种子状态：</label>
                                <div class="layui-input-block">
                                    <select name="status" lay-verify="required">
                                        <option value="1" ${data.status == 1 ? 'selected' : ''}>进行中</option>
                                        <option value="99" ${data.status == 99 ? 'selected' : ''}>完结</option>
                                    </select>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">下载状态：</label>
                                <div class="layui-input-block">
                                    <select name="down_status" lay-verify="required">
                                        <option value="0" ${data.down_status == 0 ? 'selected' : ''}>待下载</option>
                                        <option value="1" ${data.down_status == 1 ? 'selected' : ''}>下载中</option>
                                        <option value="2" ${data.down_status == 2 ? 'selected' : ''}>下载完成</option>
                                    </select>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">MediaInfo状态：</label>
                                <div class="layui-input-block">
                                    <select name="mediaInfo_status" lay-verify="required">
                                        <option value="0" ${data.mediaInfo_status == 0 ? 'selected' : ''}>未获取</option>
                                        <option value="2" ${data.mediaInfo_status == 2 ? 'selected' : ''}>获取完成</option>
                                    </select>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">重试次数：</label>
                                <div class="layui-input-block">
                                    <input type="number" name="mediainfo_retry_count" value="${data.mediainfo_retry_count || 0}" class="layui-input" min="0" max="99" lay-verify="number">
                                </div>
                            </div>
                        </form>
                    </div>
                `,
                btn: ['确定', '取消'],
                yes: function (index) {
                    let formData = form.val('edit-status-form');
                    let loading = layer.load();
                    $.ajax({
                        url: UPDATE_API,
                        data: {
                            id: data.id,
                            status: formData.status,
                            down_status: formData.down_status,
                            mediaInfo_status: formData.mediaInfo_status,
                            mediainfo_retry_count: formData.mediainfo_retry_count
                        },
                        dataType: "json",
                        type: "post",
                        success: function (res) {
                            layer.close(loading);
                            if (res.code) {
                                return layui.popup.failure(res.msg);
                            }
                            layer.close(index);
                            return layui.popup.success("状态更新成功", refreshTable);
                        },
                        error: function () {
                            layer.close(loading);
                            return layui.popup.failure("网络错误，状态更新失败");
                        }
                    });
                }
            });

            // 重新渲染表单
            form.render();
        }

        // 删除一行
        let remove = function (obj) {
            return doRemove(obj.data[PRIMARY_KEY]);
        }

        // 删除多行
        let batchRemove = function (obj) {
            let checkIds = common.checkField(obj, PRIMARY_KEY);
            if (checkIds === "") {
                layui.popup.warning("未选中数据");
                return false;
            }
            doRemove(checkIds.split(","));
        }

        // 执行删除
        let doRemove = function (ids) {
            let data = {};
            data[PRIMARY_KEY] = ids;
            layer.confirm("确定删除?", {
                icon: 3,
                title: "提示"
            }, function (index) {
                layer.close(index);
                let loading = layer.load();
                $.ajax({
                    url: DELETE_API,
                    data: data,
                    dataType: "json",
                    type: "post",
                    success: function (res) {
                        layer.close(loading);
                        if (res.code) {
                            return layui.popup.failure(res.msg);
                        }
                        return layui.popup.success("操作成功", refreshTable);
                    }
                })
            });
        }

        // 刷新表格数据
        window.refreshTable = function () {
            table.reloadData("data-table", {
                scrollPos: "fixed",
                done: function (res, curr) {
                    if (curr > 1 && res.data && !res.data.length) {
                        curr = curr - 1;
                        table.reloadData("data-table", {
                            page: {
                                curr: curr
                            },
                        })
                    }
                }
            });
        }
    })

</script>
</body>
</html>
